ScalaCheck: Property-based testing for Scala

ScalaCheck is a library written in Scala and used for automated property-based testing of Scala or Java programs. ScalaCheck was originally inspired by the Haskell library QuickCheck, but has also ventured into its own.

ScalaCheck has no external dependencies other than the Scala runtime, and works great with sbt, the Scala build tool. It is also fully integrated in the test frameworks ScalaTest, specs2 and LambdaTest. You can also use ScalaCheck completely standalone, with its built-in test runner.

ScalaCheck is used by several prominent Scala projects, for example the Scala compiler and the Akka concurrency framework.

News

Quick start

Specify some of the methods of java.lang.String like this:

import org.scalacheck.Properties
import org.scalacheck.Prop.forAll

object StringSpecification extends Properties("String") {

  property("startsWith") = forAll { (a: String, b: String) =>
    (a+b).startsWith(a)
  }

  property("concatenate") = forAll { (a: String, b: String) =>
    (a+b).length > a.length && (a+b).length > b.length
  }

  property("substring") = forAll { (a: String, b: String, c: String) =>
    (a+b+c).substring(a.length, a.length+b.length) == b
  }

}

If you use sbt add the following dependency to your build file:

libraryDependencies += "org.scalacheck" %% "scalacheck" % "1.14.1" % "test"

Put your ScalaCheck properties in src/test/scala, then use the test task to check them:

$ sbt test
+ String.startsWith: OK, passed 100 tests.
! String.concat: Falsified after 0 passed tests.
> ARG_0: ""
> ARG_1: ""
+ String.substring: OK, passed 100 tests.

As you can see, the second property was not quite right. ScalaCheck discovers this and presents the arguments that make the property fail, two empty strings. The other two properties both pass 100 test rounds, each with a randomized set of input parameters.

You can also use ScalaCheck standalone, since it has a built-in command line test runner. Compile and run like this:

$ scalac -cp scalacheck_2.11-1.14.1.jar StringSpecification.scala

$ scala -cp .:scalacheck_2.11-1.14.1.jar StringSpecification